package com.css.zfzx.sjcj.modules.hddcTargetRegion.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.repository.entity.HddcB1GeomorlnonfractbltEntity;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.viewobjects.HddcB1GeomorlnonfractbltVO;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.repository.HddcTargetregionNativeRepository;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.repository.HddcTargetregionRepository;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.repository.entity.HddcTargetregionEntity;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.service.HddcTargetregionService;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.viewobjects.HddcTargetregionQueryParams;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.viewobjects.HddcTargetregionVO;
import com.css.zfzx.sjcj.modules.hddcWorkRegion.repository.entity.HddcWorkregionEntity;
import com.css.zfzx.sjcj.modules.hddcWorkRegion.service.HddcWorkregionService;
import org.apache.jasper.tagplugins.jstl.core.ForEach;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author zyb
 * @date 2020-11-30
 */
@Service
public class HddcTargetregionServiceImpl implements HddcTargetregionService {

	@Autowired
    private HddcTargetregionRepository hddcTargetregionRepository;
    @Autowired
    private HddcTargetregionNativeRepository hddcTargetregionNativeRepository;
    @Autowired
    private HddcWorkregionService hddcWorkregionService;

    @Override
    public JSONObject queryHddcTargetregions(HddcTargetregionQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcTargetregionEntity> hddcTargetregionPage = this.hddcTargetregionNativeRepository.queryHddcTargetregions(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcTargetregionPage);
        return jsonObject;
    }


    @Override
    public HddcTargetregionEntity getHddcTargetregion(String id) {
        HddcTargetregionEntity hddcTargetregion = this.hddcTargetregionRepository.findById(id).orElse(null);
         return hddcTargetregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcTargetregionEntity saveHddcTargetregion(HddcTargetregionEntity hddcTargetregion) {
        String uuid = UUIDGenerator.getUUID();
        hddcTargetregion.setUuid(uuid);
        hddcTargetregion.setCreateUser(PlatformSessionUtils.getUserId());
        hddcTargetregion.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcTargetregion.setIsValid("1");
        this.hddcTargetregionRepository.save(hddcTargetregion);
        return hddcTargetregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcTargetregionEntity updateHddcTargetregion(HddcTargetregionEntity hddcTargetregion) {
        UpdateUtil.copyNullProperties(hddcTargetregionRepository.findByUuidAndIsValid(hddcTargetregion.getUuid(), "1"
                ), hddcTargetregion);
        hddcTargetregion.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcTargetregion.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcTargetregionRepository.save(hddcTargetregion);
        return hddcTargetregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcTargetregions(List<String> ids) {
        List<HddcTargetregionEntity> hddcTargetregionList = this.hddcTargetregionRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcTargetregionList) && hddcTargetregionList.size() > 0) {
            for(HddcTargetregionEntity hddcTargetregion : hddcTargetregionList) {
                hddcTargetregion.setIsValid("0");
                hddcTargetregion.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcTargetregion.setUpdateTime(new Date());
                this.hddcTargetregionRepository.save(hddcTargetregion);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcTargetregionQueryParams queryParams, HttpServletResponse response) {
        List<HddcTargetregionEntity> yhDisasterEntities = hddcTargetregionNativeRepository.exportYhDisasters(queryParams);
        List<HddcTargetregionVO> list=new ArrayList<>();
        for (HddcTargetregionEntity entity:yhDisasterEntities) {
            HddcTargetregionVO yhDisasterVO=new HddcTargetregionVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"目标区-面","目标区-面",HddcTargetregionVO.class,"目标区-面.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcTargetregionVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcTargetregionVO.class, params);
            List<HddcTargetregionVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcTargetregionVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcTargetregionVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public HddcTargetregionEntity findById(String id) {
        HddcTargetregionEntity hddcTargetregionEntity= hddcTargetregionRepository.findbyId(id);
        return hddcTargetregionEntity;
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcTargetregionVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcTargetregionEntity yhDisasterEntity = new HddcTargetregionEntity();
            HddcTargetregionVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcTargetregion(yhDisasterEntity);
        }
    }
    @Transactional
    @Override
    public int dataQualityCheck() {
        List<HddcTargetregionEntity> listAll=hddcTargetregionRepository.findByAll();
        for(HddcTargetregionEntity hddc:listAll){
            String str="";
            if (StringUtils.isEmpty(hddc.getWorkregionid())) {
                continue;
            }
            HddcWorkregionEntity hddcWorkregionEntity = hddcWorkregionService.findById(hddc.getWorkregionid());
            if (hddcWorkregionEntity==null){
                hddcTargetregionRepository.updateStatus("2","质检失败",hddc.getUuid());
                 continue;
            }
            if(hddcWorkregionEntity.getTrarea()!=hddc.getTrarea()){
                str +="目标区面积失败！";
            }
            if(hddcWorkregionEntity.getMappingarea()!=hddc.getMappingarea()){
                str +="地质填图面积失败！";
            }
            if(hddcWorkregionEntity.getRsprocess()!=hddc.getRsprocess()){
                str +="遥感影像处理数目失败！";
            }
            if(hddcWorkregionEntity.getFieldsvyptcount()!=hddc.getFieldsvyptcount()){
                str +="野外观测点数失败！";
            }
            if(hddcWorkregionEntity.getTrenchcount()!=hddc.getTrenchcount()){
                str +="探槽数失败！";
            }
            if(!hddcWorkregionEntity.getTrenchvolume().equals(hddc.getTrenchvolume())){
                str +="探测总土方量失败！";
            }
            if(hddcWorkregionEntity.getDrillcount()!=hddc.getDrillcount()){
                str +="钻孔数失败！";
            }
            if(hddcWorkregionEntity.getDrilllength()!=hddc.getDrilllength()){
                str +="钻孔进尺失败！";
            }
            if(hddcWorkregionEntity.getDrilllength()!=hddc.getDrilllength()){
                str +="钻孔进尺失败！";
            }
            if(hddcWorkregionEntity.getGphwellcount()!=hddc.getGphwellcount()){
                str +="地球物理测井数失败！";
            }
            if(hddcWorkregionEntity.getCollectedsamplecount()!=hddc.getCollectedsamplecount()){
                str +="采集样品总数失败！";
            }
            if(hddcWorkregionEntity.getSamplecount()!=hddc.getSamplecount()){
                str +="送样总数失败！";
            }
            if(hddcWorkregionEntity.getDatingsamplecount()!=hddc.getDatingsamplecount()){
                str +="获得测试结果样品数失败！";
            }
            if(hddcWorkregionEntity.getGeomorphysvyprojectcount()!=hddc.getGeomorphysvyprojectcount()){
                str +="微地貌测量工程总数失败！";
            }
            if(hddcWorkregionEntity.getSeismicprojectcount()!=hddc.getSeismicprojectcount()){
                str +="地震监测工程数失败！";
            }
            if(hddcWorkregionEntity.getCrustaldfmprojectcount()!=hddc.getCrustaldfmprojectcount()){
                str +="地形变监测工程数失败！";
            }
            if(hddcWorkregionEntity.getGeophysicalsvyprojectcount()!=hddc.getGeophysicalsvyprojectcount()){
                str +="地球物理探测工程数失败！";
            }
            if(hddcWorkregionEntity.getGeochemicalprojectcount()!=hddc.getGeochemicalprojectcount()){
                str +="地球化学探测工程数失败！";
            }
            if(hddcWorkregionEntity.getNumsimulationcount()!=hddc.getNumsimulationcount()){
                str +="断层三维数值模拟总数失败！";
            }
            if(str.isEmpty()){
                str +="质检成功";
                hddcTargetregionRepository.updateStatus("1",str,hddc.getUuid());
            }else{
                hddcTargetregionRepository.updateStatus("2",str,hddc.getUuid());
            }
        }

        return 1;
    }
}
